package com.qq.shrio;


import com.qq.UserMapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;


public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserMapper userMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String name = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<String> permissionList = new ArrayList<>();
        info.addStringPermissions(permissionList);

        //动态获取权限字段
        List<String> roles = userMapper.selectRoleByName(name);
        for (String r:roles) {
            info.addRole(r);
        }
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取姓名+密码
        UsernamePasswordToken t = (UsernamePasswordToken) token;
        String name = t.getUsername();
        String password = new String(t.getPassword());

        //通过名字动态查询认证
        User user = userMapper.selectUserByNamePassword(name, password);
        if (user == null)
            throw new AuthenticationException();
        else
            return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
    }
}
